package com.jch.dm11_pipeline.reusable;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;

/**
 * 线程停止标志
 * 每个ExecutorService实例对应唯一的一个TerminationToken实例
 * <p>
 * 使用Two-phase Termination模式来停止多个Pipe实例所共用的线程池实例
 */
public class TerminationToken extends com.jch.dm3_two_phase_termination.reusable_code.TerminationToken {

    private final static ConcurrentMap<ExecutorService, TerminationToken> INSTANCES_MAP = new ConcurrentHashMap<>();

    private TerminationToken() {
    }

    void setIsToShutdown() {
        this.toShutdown = true;
    }

    static TerminationToken newInstance(ExecutorService executorService) {
        TerminationToken token = INSTANCES_MAP.get(executorService);
        if (null == token) {
            token = new TerminationToken();
            TerminationToken existingToken = INSTANCES_MAP.putIfAbsent(executorService, token);
            if (null != existingToken) {
                token = existingToken;
            }
        }
        return token;
    }
}
